#!/usr/bin/env python
#coding=utf-8
"""
socket server
"""
import SocketServer, commands

class EchoServiceHandler(SocketServer.BaseRequestHandler):
	"""
	get req from client
	"""
	def handle(self):
		while True:
			self.data = self.request.recv(1024).strip()
			if not self.data: break

			self.res = commands.getstatusoutput(self.data)
			# print self.data[0], self.data[1]
			print self.res

			if self.res[0] == 0:
				if self.res[1] == '':
					self.res_back = 'command success ok %s' % self.data
				else:
					self.res_back = self.res[1]
			else:
				self.res_back = 'command not correct %s' % self.data

			print 'res_back', self.res_back

			print self.data

			self.request.sendall(self.res_back)

if __name__ == '__main__':
	host, port = '127.0.0.1', 50008

	#forking tcp，长链接，多线程
	#ForkingUDPServer
	#ForkingTCPServer
	#ThreadingUDPServer
	#ThreadingTCPServer
	server = SocketServer.ForkingUDPServer((host, port), EchoServiceHandler)
	server.allow_reuse_address = True	#允许地址重用
	server.serve_forever()
